//
//  InitialViewController.m
//  ArandaTest
//
//  Created by Camilo Cadena on 2/18/15.
//  Copyright (c) 2015 Camilo Cadena. All rights reserved.
//

#import "InitialViewController.h"
#import "TvSeriesController.h"
#import "SeriesDetailViewController.h"

@interface InitialViewController ()

@end

@implementation InitialViewController
@synthesize seriesArray;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.seriesArray = [[NSMutableArray alloc] init];
    [self requestSeriesWithString:@"a" andpage:1];
    
    //Set Text value change event
    [self.searchField addTarget:self
                  action:@selector(textFieldDidChange:)
        forControlEvents:UIControlEventEditingChanged];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark - UITextField Protocol
//Check for a change in the search textfield and make a new request
-(void)textFieldDidChange:(UITextField *)textField{
    if(textField.text.length >0){
        [self requestSeriesWithString:textField.text andpage:1];
    }

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if(textField.text.length >0){
        [self requestSeriesWithString:textField.text andpage:1];
    }
    
    [self.searchField resignFirstResponder];
    return YES;
}

#pragma mark - UICollectionView Datasource
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    return [self.seriesArray count];
}

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"customCollectionCell" forIndexPath:indexPath];
    
    [cell updateCell:[self.seriesArray objectAtIndex:indexPath.row]];
    
    //Check for last cell in table and request the next page. The reuqest will be made only if there are pages left
    if(indexPath.row == self.seriesArray.count-1){
        self.currentPage++;
        if(self.currentPage <= self.pagesAvailable){
            [self requestSeriesWithString:self.searchField.text andpage:self.currentPage];
        }
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    [self.searchField resignFirstResponder];
    SeriesObject *item = [self.seriesArray objectAtIndex:indexPath.row];
    [self requestAllSeasonsforSelectedTvShow:item];
    
}


#pragma mark - Request Services Methods
-(void)requestSeriesWithString:(NSString *)query andpage:(int)page
{
    //Initializes manager and request the TV series with the search Bar string
    TvSeriesController *manager = [[TvSeriesController alloc] init];
    [manager requestSeriesUsingString:query page:[NSString stringWithFormat:@"%d",page] andCompletionBlock:^(id response){
        //Validates if the result is an array, otherwise shows error message
        if([response isKindOfClass:[NSDictionary class]]){
            
            if(page == 1){
                [self.seriesArray removeAllObjects];
            }
            
            [self.seriesArray addObjectsFromArray:[response valueForKey:@"results"]];
            self.pagesAvailable = [[response valueForKey:@"pages"] intValue];
            self.currentPage = page;
            [self.collection reloadData];
        }
    }];
}

//Request all season for tvShow
-(void)requestAllSeasonsforSelectedTvShow:(SeriesObject *)item{
    //usar el series_id del objeto
    TvSeriesController *controller = [[TvSeriesController alloc] init];
    [controller requestAllSeasonsForSelectedSeriesId:item.series_id andCompletionBlock:^(id response){
        if([response isKindOfClass:[NSArray class]]){
            
            NSArray *seasonsArray = [[NSArray alloc] initWithArray:response];
            if(seasonsArray.count>0){
                UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                SeriesDetailViewController * viewc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"SeriesDetailViewController"];
                viewc.seasonsArray = seasonsArray;
                viewc.item = item;
                [self.navigationController pushViewController:viewc animated:YES];
            }else{
                //Show without seasons available
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry!" message:@"No available seasons for this Show" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                [alert show];
            }
        }else{
            //Error in request, please check internet connection
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please check your internet connection and try again!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
}

@end

